package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.ParamHelper;
import com.fadadianqi.logistics.customer.model.Customer;
import com.fadadianqi.logistics.customer.service.AccountService;
import com.fadadianqi.logistics.customer.service.CustomerService;
import com.fadadianqi.logistics.sell.model.Bill;
import com.fadadianqi.logistics.sell.service.BillService;
import com.fadadianqi.logistics.sell.service.PaymentService;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class PaymentController {

    @RequestMapping(value = "/a/ajax/customer/payment/form", method = RequestMethod.GET)
    public String showForm(HttpServletRequest request, ModelMap modelMap) {
        String billId = ParamHelper.getId(request, null);
        Bill bill = billService.getById(billId);
        modelMap.put("bill", bill);

        Customer customer = customerService.getById(bill.getCustomerId());
        modelMap.put("customer", customer);

        modelMap.put("balance", accountService.getBalance(customer));

        double sumPaid = paymentService.sumPaid(bill);
        modelMap.put("sumPaid", sumPaid);
        return "/admin/customer/paymentForm";
    }

    @RequestMapping(value = "/a/ajax/customer/payment/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> save(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        String billId = ParamHelper.getId(request, null);
        Double cash = ParamUtils.getDoubleParameter(request, "cash", 0L);
        Boolean useBalance = ParamUtils.getBoolean(request, "useBalance", Boolean.TRUE);
        Bill bill = billService.getById(billId);
        paymentService.payment(bill, useBalance, cash);
        rs = new AjaxResult(bill, Boolean.TRUE, StringHelper.EMPTY);
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @Autowired
    private BillService billService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AccountService accountService;
}
